import CryptoJS from 'crypto-js';
let xunfeiSocketTask = {}
let toAudioText = '你好啊'
export const getWebsocketUrl = async function() {
	const APPID = '153511e4'
	const APISecret = 'NjI2NDgxOGQzMzYwMGY5OTgxMWI2OGQ2'
	const APIKey = 'e9be89532ac0b69d59752a5317b60341'
	// 合成讯飞语音请求地址
	return await new Promise((resolve, reject) => {
		var apiKey = APIKey; // 讯飞控制台查看
		var apiSecret = APISecret; // 讯飞控制台查看
		var url = 'wss://tts-api.xfyun.cn/v2/tts';
		var host = 'http://192.168.31.171:8081'; // 请求的主机地址
		var date = new Date().toGMTString();
		var algorithm = 'hmac-sha256';
		var headers = 'host date request-line';
		var signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v2/tts HTTP/1.1`;
		var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret);
		var signature = CryptoJS.enc.Base64.stringify(signatureSha);
		var authorizationOrigin =
			`api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
		var authorization = base64_encode(authorizationOrigin);
		url = `${url}?authorization=${authorization}&date=${date}&host=${host}`;
		resolve(url);
	});
}
export const linkXunfeiSocket = async function() {
	// 连接讯飞Socket服务器
	let url = await getWebsocketUrl();
	console.log("url: ", url);
	await new Promise((resolve, reject) => {
		this.XunfeiSocketTask = uni.connectSocket({
			url: encodeURI(url),
			header: {
				'content-type': 'application/json'
			},
			success: () => {
				console.log(`讯飞 connect成功`);
				resolve();
			},
			fail: () => {
				console.log('讯飞 connect失败');
				reject();
			}
		});
	});

	console.log("XunfeiSocketTaskaaaaaaaaaaaaaaaaa: ", this.XunfeiSocketTask);
	// this.xunfeiSocketTask = xunfeiSocketTask;
	initXunFei(this.XunfeiSocketTask);
}

function initXunFei(xunfeiSocketTask) {

	console.log("xunfeiSocketTask: ", xunfeiSocketTask);
	// 监听消息
	xunfeiSocketTask.onMessage(res => {
		// console.log('接收讯飞消息');
		this.result(res.data);
	});
	xunfeiSocketTask.onOpen(() => {
		// console.log('讯飞websocket打开');
		webSocketSend(xunfeiSocketTask);
	});
	xunfeiSocketTask.onClose(res => {
		clearTimeout(this.playTimeout);
		// console.error('讯飞断开');
	});
	xunfeiSocketTask.onError(err => {
		// console.error('讯飞连接错误', err);
	});
}

function webSocketSend(xunfeiSocketTask) {
	const APPID = '153511e4'
	const APISecret = 'NjI2NDgxOGQzMzYwMGY5OTgxMWI2OGQ2'
	const APIKey = 'e9be89532ac0b69d59752a5317b60341'
	let params = {
		common: {
			app_id: APPID // 讯飞控制台查看
		},
		business: {
			aue: 'lame', // 音频编码表示mp3格式，当aue=lame时需传参sfl=1
			sfl: 1,
			vcn: 'xiaoyan', // 发音人选择
			tte: 'UTF8'
		},
		data: {
			status: 2,
			text: CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(toAudioText))
		}
	};

	xunfeiSocketTask.send({
		data: JSON.stringify(params),
		success: res => {
			// console.log('发出讯飞消息');
		},
		fail: err => {
			// console.log('发出讯飞消息失败', err);
		}
	});
}

function base64_encode(str) {
	// 编码，配合encodeURIComponent使用
	var c1, c2, c3;
	var base64EncodeChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
	var i = 0,
		len = str.length,
		strin = '';
	while (i < len) {
		c1 = str.charCodeAt(i++) & 0xff;
		if (i == len) {
			strin += base64EncodeChars.charAt(c1 >> 2);
			strin += base64EncodeChars.charAt((c1 & 0x3) << 4);
			strin += '==';
			break;
		}
		c2 = str.charCodeAt(i++);
		if (i == len) {
			strin += base64EncodeChars.charAt(c1 >> 2);
			strin += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xf0) >> 4));
			strin += base64EncodeChars.charAt((c2 & 0xf) << 2);
			strin += '=';
			break;
		}
		c3 = str.charCodeAt(i++);
		strin += base64EncodeChars.charAt(c1 >> 2);
		strin += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xf0) >> 4));
		strin += base64EncodeChars.charAt(((c2 & 0xf) << 2) | ((c3 & 0xc0) >> 6));
		strin += base64EncodeChars.charAt(c3 & 0x3f);
	}
	return strin;
}